package com.sfac.springboot.modules.common.service.Impl;

import com.sfac.springboot.config.ResourceConfigBean;
import com.sfac.springboot.modules.common.service.ImageService;
import com.sfac.springboot.modules.common.vo.Result;
import com.sfac.springboot.utils.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @Description ImageServiceImpl
 * @Author JiangHu
 * @Date 2022/8/23 10:25
 */
@Service
public class ImageServiceImpl implements ImageService {

	public final static Logger LOGGER = LoggerFactory.getLogger(ImageServiceImpl.class);
	@Autowired
	private ResourceConfigBean resourceConfigBean;
	@Value("${project.artifactId}")
	private String artifactId;

	@Override
	public Result<String> uploadImage(MultipartFile file, String imageTypeName) {

		// 判断图片是否为空
		if (file.isEmpty()) {
			return new Result<>(Result.ResultStatus.FAILD.code, "File is empty.");
		}

		// 对图片进行校验
		if (!FileUtil.isImage(file)) {
			return new Result<>(Result.ResultStatus.FAILD.code,
					"Please select a image.");
		}

		// 图片重命名
		String imageName = String.format("%s.%s",
				System.currentTimeMillis(),
				FileUtil.getFileType(file.getOriginalFilename())
		);

		// 构建目标文件夹，如果不存在则创建
		String destFolder = String.format("%s%s/%s",
				System.getProperty("os.name").toLowerCase().startsWith("win") ?
						resourceConfigBean.getLocalPathForWin() :
						resourceConfigBean.getLocalPathForLin(),
				artifactId,
				imageTypeName
		);
		File destFolderFile = new File(destFolder);
		if (!destFolderFile.exists()) {
			destFolderFile.mkdirs();
		}

		// 构造图片存放的绝对路径
		String destPath = String.format("%s/%s", destFolder, imageName);

		// 构造图片相对路径
		String relativePath = String.format("%s%s/%s/%s",
				resourceConfigBean.getResourcePath(),
				artifactId,
				imageTypeName,
				imageName
				);

		// 保存图片
		try {
			file.transferTo(new File(destPath));

		} catch (IOException e) {
			e.printStackTrace();
			LOGGER.info(e.getMessage());
			return new Result<>(Result.ResultStatus.FAILD.code,
					"Uploud image failed.");
		}

		// 返回结果集
		return new Result<>(Result.ResultStatus.SUCCESS.code,
				"Uploud image success.", relativePath);
	}
}
